package org.net5ijy.commons.http.oss;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;

/**
 * OssClient
 *
 * @author xuguofeng
 * @date 2020/9/15 11:16
 */
@Slf4j
public class OssClient {

  private static OSSClient ossClient;

  static {

    CredentialsProvider credentialsProvider =
        new DefaultCredentialProvider("", "");

    ClientConfiguration conf = new ClientConfiguration();

    conf.setProxyHost("proxy.******.com");
    conf.setProxyPort(8080);
    conf.setProxyUsername("******");
    conf.setProxyPassword("******");

    ossClient = new OSSClient("https://oss-cn-shanghai.aliyuncs.com", credentialsProvider, conf);
  }

  public static String generateSignedUrl(String filename, long expiresAfter) {

    // 过期时间
    Date expires = new Date(System.currentTimeMillis() + expiresAfter);

    GeneratePresignedUrlRequest generatePresignedUrlRequest =
        new GeneratePresignedUrlRequest("****", filename);

    generatePresignedUrlRequest.setExpiration(expires);

    URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);

    return url.toString();
  }

  public static void main(String[] args) {
    String url = OssClient.generateSignedUrl("200M.7z", 3600000);
    System.out.println(url);
  }

  private static void upload() {

    String key = "test-app/" + System.currentTimeMillis() + "/Tengamishouji.pc6.apk";
    System.out.println(key);

    try {
      PutObjectResult putObjectResult = ossClient.putObject(
          "",
          key,
          new FileInputStream("D:\\Tengamishouji.pc6.apk"));

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
